<template>
  <div class="page-container">
    <!-- 筛选区卡片 -->
    <div class="filter-card">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item label="入库单编号">
          <el-input v-model="searchForm.inboundListCode" placeholder="请输入入库单编号" />
        </el-form-item>
        <el-form-item label="入库单名称">
          <el-input v-model="searchForm.inboundListName" placeholder="请输入入库单名称" />
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.informCode" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="入库日期">
          <el-date-picker v-model="searchForm.inboundListTime" type="date" placeholder="选择入库日期" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="onAdd">新增</el-button>
      <el-button type="success" :icon="Edit" @click="onEditSelected">修改</el-button>
      <el-button type="danger" :icon="Delete" @click="onDeleteSelected">删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="inboundListCode" label="入库单编号" width="150" />
      <el-table-column prop="inboundListName" label="入库单名称" width="150" />
      <el-table-column prop="supplierName" label="供应商名称" />
      <el-table-column prop="inboundListTime" label="入库日期" />
      <el-table-column prop="purchaseOrderCode" label="采购订单号" />
      <el-table-column prop="states" label="单据状态" width="100">
        <template #default="{ row }">
          <span>{{ stateText(row.states) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <div class="table-action-btns">
            <template v-if="row.states === 0">
              <el-button type="primary" size="small" @click="onEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="onDelete(row)">删除</el-button>
            </template>
            <template v-else-if="row.states === 1">
              <el-button type="success" size="small">执行上架</el-button>
            </template>
            <!-- 已上架和已取消不显示任何按钮 -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 16px 0; text-align: right;">
      <el-pagination
        :current-page="pagination.pageIndex"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
      />
    </div>

    <!-- 新增入库单弹窗 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="添加物料入库单" 
      width="900px"
      :close-on-click-modal="false"
      destroy-on-close
      class="custom-dialog"
    >
      <div class="dialog-content">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="dialog-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单编号" prop="inboundListCode" required>
                <div class="code-input-container">
                  <el-input v-model="addForm.inboundListCode" :disabled="addForm.autoGenerate" placeholder="请输入入库单编号" />
                  <el-switch
                    v-model="addForm.autoGenerate"
                    class="auto-generate"
                    active-text="自动生成"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称" prop="inboundListName" required>
                <el-input v-model="addForm.inboundListName" placeholder="请输入入库单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库日期" prop="inboundListTime" required>
                <el-date-picker v-model="addForm.inboundListTime" type="date" placeholder="请选择入库日期" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName" required>
                <div class="input-with-icon">
                  <el-input v-model="addForm.supplierName" placeholder="请选择供应商" disabled />
                  <el-button icon="Search" class="search-btn" circle style="visibility: hidden;"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到货通知单">
                <div class="input-with-icon">
                  <el-input v-model="addForm.noticeOrder" placeholder="请选择到货通知单" />
                  <el-button icon="Search" class="search-btn" circle @click="openArrivalNoticeDialog('add')"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购订单编号">
                <el-input v-model="addForm.purchaseOrderCode" placeholder="请输入采购订单编号" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="onAddSubmit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑入库单弹窗 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑物料入库单" 
      width="900px"
      :close-on-click-modal="false"
      destroy-on-close
      class="custom-dialog"
    >
      <div class="dialog-content">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px" class="dialog-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单编号" prop="inboundListCode" required>
                <el-input v-model="editForm.inboundListCode" disabled placeholder="请输入入库单编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称" prop="inboundListName" required>
                <el-input v-model="editForm.inboundListName" placeholder="请输入入库单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库日期" prop="inboundListTime" required>
                <el-date-picker v-model="editForm.inboundListTime" type="date" placeholder="请选择入库日期" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName" required>
                <div class="input-with-icon">
                  <el-input v-model="editForm.supplierName" placeholder="请选择供应商" disabled />
                  <el-button icon="Search" class="search-btn" circle style="visibility: hidden;"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到货通知单">
                <div class="input-with-icon">
                  <el-input v-model="editForm.informCode" placeholder="请选择到货通知单" />
                  <el-button icon="Search" class="search-btn" circle @click="openArrivalNoticeDialog('edit')"></el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购订单编号">
                <el-input v-model="editForm.purchaseOrderCode" placeholder="请输入采购订单编号" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="onEditSubmit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 供应商选择弹窗 -->
    <el-dialog
      v-model="supplierDialogVisible"
      title="供应商选择"
      width="900px"
      :close-on-click-modal="false"
      destroy-on-close
      class="custom-dialog"
    >
      <div class="dialog-content">
        <el-form :inline="true" :model="supplierSearchForm" class="filter-form">
          <el-form-item label="供应商编码">
            <el-input v-model="supplierSearchForm.supplierCode" placeholder="请输入供应商编码" />
          </el-form-item>
          <el-form-item label="供应商名称">
            <el-input v-model="supplierSearchForm.supplierName" placeholder="请输入供应商名称" />
          </el-form-item>
          <el-form-item label="供应商简称">
            <el-input v-model="supplierSearchForm.supplierReferred" placeholder="请输入供应商简称" />
          </el-form-item>
          <el-form-item label="供应商评级">
            <el-select v-model="supplierSearchForm.supplierRating" placeholder="请选择评级">
              <el-option label="全部" value="" />
              <el-option label="0" value="0" />
              <el-option label="1" value="1" />
              <el-option label="2" value="2" />
              <el-option label="3" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否锁定">
            <el-select v-model="supplierSearchForm.isLock" placeholder="是否锁定">
              <el-option label="全部" value="" />
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchSuppliers">搜索</el-button>
            <el-button @click="resetSupplierSearch">重置</el-button>
          </el-form-item>
        </el-form>
        
        <el-table :data="supplierTableData" border>
          <el-table-column width="60" align="center">
            <template #default="{ row }">
              <el-radio v-model="selectedSupplierId" :label="row.id" @change="() => handleSupplierSelect(row)">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="supplierCode" label="供应商编码" />
          <el-table-column prop="supplierName" label="供应商名称" />
          <el-table-column prop="supplierReferred" label="供应商简称" />
          <el-table-column prop="level" label="供应商等级" />
          <el-table-column prop="supplierRating" label="供应商评分" />
          <el-table-column prop="phone" label="供应商电话" />
          <el-table-column prop="isLock" label="是否锁定">
            <template #default="{ row }">
              <span>{{ row.isLock ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>
        <div style="margin: 16px 0; text-align: right;">
          <el-pagination
            :current-page="supplierPagination.pageIndex"
            :page-size="supplierPagination.pageSize"
            :total="supplierPagination.total"
            @current-change="handleSupplierPageChange"
            layout="total, prev, pager, next"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="supplierDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="confirmSupplierSelect">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 到货通知单选择弹窗 -->
    <el-dialog
      v-model="arrivalNoticeDialogVisible"
      title="到货通知单选择"
      width="1200px"
      top="5vh"
      :close-on-click-modal="false"
      destroy-on-close
      class="custom-dialog"
    >
      <div class="dialog-header">
        到货通知单选择
      </div>
      
      <div class="notice-search-area">
        <el-form :inline="true" :model="arrivalNoticeSearchForm" class="filter-form">
          <el-form-item label="通知单编号">
            <el-input v-model="arrivalNoticeSearchForm.noticeCode" placeholder="请输入通知单编号" />
          </el-form-item>
          <el-form-item label="通知单名称">
            <el-input v-model="arrivalNoticeSearchForm.noticeName" placeholder="请输入通知单名称" />
          </el-form-item>
          <el-form-item label="采购订单编号">
            <el-input v-model="arrivalNoticeSearchForm.purchaseOrderCode" placeholder="请输入采购订单编号" />
          </el-form-item>
          <el-form-item label="供应商名称">
            <el-input v-model="arrivalNoticeSearchForm.supplierName" placeholder="请输入供应商名称" />
          </el-form-item>
          <el-form-item label="到货日期">
            <el-date-picker 
              v-model="arrivalNoticeSearchForm.deliveryDate" 
              type="date" 
              placeholder="选择预期到货日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchArrivalNotices">搜索</el-button>
            <el-button @click="resetArrivalNoticeSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="notice-table-wrapper">
        <el-table
          :data="arrivalNoticeTableData"
          border
          height="400px"
          @row-click="handleNoticeRowClick"
          highlight-current-row
          class="custom-table">
          <el-table-column
            type="radio"
            width="50">
            <template #default="scope">
              <el-radio v-model="selectedNoticeId" :label="scope.row.id">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column
            prop="noticeCode"
            label="通知单编号"
            width="150"
            align="center" />
          <el-table-column
            prop="noticeName"
            label="通知单名称"
            width="150"
            align="center" />
          <el-table-column
            prop="purchaseOrderCode"
            label="采购订单编号"
            width="150"
            align="center" />
          <el-table-column
            prop="supplierName"
            label="供应商名称"
            align="center" />
          <el-table-column
            prop="contactPerson"
            label="联系人"
            align="center" />
          <el-table-column
            prop="phone"
            label="联系方式"
            align="center" />
          <el-table-column
            prop="deliveryDate"
            label="到货日期"
            width="100"
            align="center">
            <template #default="scope">
              {{ scope.row.deliveryDate ? scope.row.deliveryDate.substring(0, 10) : '' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="单据状态"
            width="100"
            align="center" />
        </el-table>
        
        <div class="notice-pagination-area">
          <span class="total-count">共 {{ arrivalNoticePagination.total }} 条</span>
          <el-pagination
            @size-change="handleArrivalNoticeSizeChange"
            @current-change="handleArrivalNoticePageChange"
            v-model:current-page="arrivalNoticePagination.pageIndex"
            v-model:page-size="arrivalNoticePagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="sizes, prev, pager, next, jumper"
            :total="arrivalNoticePagination.total" />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="arrivalNoticeDialogVisible = false" class="footer-btn cancel-btn">取 消</el-button>
          <el-button type="primary" @click="confirmArrivalNoticeSelect" class="footer-btn save-btn">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/api/http'

const searchForm = ref({
  inboundListCode: '',
  inboundListName: '',
  informCode: '',
  supplierName: '',
  inboundListTime: ''
})

const tableData = ref([])
const pagination = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格选中行
const selectedRows = ref<PurchaseWarehousingItem[]>([])

// 表格选中行变化
function handleSelectionChange(rows: PurchaseWarehousingItem[]) {
  selectedRows.value = rows
}

// 点击上方修改按钮
function onEditSelected() {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行修改')
    return
  }
  
  const row = selectedRows.value[0]
  // 只有草稿状态可以编辑
  if (row.states !== 0) {
    ElMessage.warning('只有草稿状态的记录可以修改')
    return
  }
  
  onEdit(row)
}

// 获取表格数据
const getTableData = async () => {
  const params = {
    pageIndex: pagination.value.pageIndex,
    pageSize: pagination.value.pageSize,
    inboundListCode: searchForm.value.inboundListCode || null,
    inboundListName: searchForm.value.inboundListName || null,
    informCode: searchForm.value.informCode || null,
    supplierName: searchForm.value.supplierName || null,
    inboundListTime: searchForm.value.inboundListTime || null
  }
  
  const response = await http.post('/api/PurchaseWarehousing/GetPurchaseWarehousing', params)
  console.log(response)
  tableData.value = response.rows || []
  pagination.value.total = response.total || 0
}

function onSearch() {
  pagination.value.pageIndex = 1
  getTableData()
}

function onReset() {
  searchForm.value = { inboundListCode: '', inboundListName: '', informCode: '', supplierName: '', inboundListTime: '' }
  pagination.value.pageIndex = 1
  getTableData()
}

function handleCurrentChange(page: number) {
  pagination.value.pageIndex = page
  getTableData()
}

const stateText = (val: number) => {
  switch(val) {
    case 0: return '草稿'
    case 1: return '待上架'
    case 2: return '已上架'
    case 3: return '已取消'
    default: return ''
  }
}

// 新增入库单相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  inboundListCode: '',
  autoGenerate: false,
  inboundListName: '',
  inboundListTime: '',
  supplierName: '',
  supplierId: '',
  noticeOrder: '',
  noticeId: '',
  informCode: '',
  purchaseOrderCode:'',
  remark: '',
  states: 0
})

const addFormRules = {
  inboundListCode: [{ required: true, message: '请输入入库单编号', trigger: 'blur' }],
  inboundListName: [{ required: true, message: '请输入入库单名称', trigger: 'blur' }],
  supplierName: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  inboundListTime: [{ required: true, message: '请选择入库日期', trigger: 'change' }]
}

function onAdd() {
  addDialogVisible.value = true
  // 清空表单
  addForm.value = {
    inboundListCode: '',
    autoGenerate: false,
    inboundListName: '',
    inboundListTime: '',
    supplierName: '',
    supplierId: '',
    noticeOrder: '',
    noticeId: '',
    informCode: '',
    purchaseOrderCode:'',
    remark: '',
    states: 0
  }
}

// 监听自动生成勾选状态
watch(() => addForm.value.autoGenerate, (newVal) => {
  if (newVal) {
    // 自动生成编号：PWH + 年月日时分秒
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    
    addForm.value.inboundListCode = `PWH${year}${month}${day}${hours}${minutes}${seconds}`
  } else {
    // 关闭自动生成时，清空编号
    addForm.value.inboundListCode = ''
  }
})

async function onAddSubmit() {
  try {
    await addFormRef.value.validate()
    // 这里调用后端接口保存数据
    await http.post('/api/PurchaseWarehousing/AddPurchaseWarehousing', addForm.value)
    addDialogVisible.value = false
    getTableData() // 刷新表格
    ElMessage.success('添加成功')
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 编辑入库单相关
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = ref({
  id: '',
  inboundListCode: '',
  inboundListName: '',
  inboundListTime: '',
  supplierName: '',
  supplierId: '',
  informCode: '',
  noticeId: '',
  purchaseOrderCode: '',
  remark: '',
  states: 0
})

// 定义入库单数据类型接口
interface PurchaseWarehousingItem {
  id: string
  inboundListCode: string
  inboundListName: string
  inboundListTime: string
  supplierName: string
  informCode?: string
  purchaseOrderCode?: string
  remark?: string
  states: number
  [key: string]: any
}

// 定义供应商类型接口
interface Supplier {
  id: string
  supplierCode: string
  supplierName: string
  supplierReferred?: string
  level?: string
  supplierRating?: number
  phone?: string
  isLock?: boolean
  remark?: string
  [key: string]: any
}

// 定义到货通知单类型接口
interface ArrivalNotice {
  id: string
  noticeCode: string
  noticeName: string
  supplierName: string
  supplierId: string
  purchaseOrderCode?: string
  contactPerson?: string
  phone?: string
  deliveryDate?: string
  status?: number
  [key: string]: any
}

// 打开编辑弹窗并填充数据
function onEdit(row: PurchaseWarehousingItem) {
  editDialogVisible.value = true
  // 填充表单数据
  editForm.value = {
    id: row.id,
    inboundListCode: row.inboundListCode,
    inboundListName: row.inboundListName,
    inboundListTime: row.inboundListTime,
    supplierName: row.supplierName,
    supplierId: row.supplierId || '',
    informCode: row.informCode || '',
    noticeId: row.noticeId || '',
    purchaseOrderCode: row.purchaseOrderCode || '',
    remark: row.remark || '',
    states: 0
  }
}

// 提交编辑表单
async function onEditSubmit() {
  try {
    await editFormRef.value.validate()
    // 调用后端接口更新数据
    await http.post('/api/PurchaseWarehousing/UpdPurchaseWarehousing', editForm.value)
    editDialogVisible.value = false
    getTableData() // 刷新表格
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 删除单条记录
async function onDelete(row: PurchaseWarehousingItem) {
  // 确认删除
  try {
    await ElMessageBox.confirm('确定要删除该入库单吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    console.log(row.inboundListCode)
    // 调用删除接口
    try {
      const params = { inboundListCode: row.inboundListCode }
      console.log('发送删除参数:', params)
      
      // 直接在URL中添加参数
      const url = `/api/PurchaseWarehousing/RemPurchaseWarehousing?inboundListCode=${encodeURIComponent(row.inboundListCode)}`
      console.log('请求URL:', url)
      
      const response = await http.post(url)
      console.log('删除接口响应:', response)
      
      ElMessage.success('删除成功')
      getTableData() // 刷新表格
    } catch (deleteError) {
      console.error('删除接口调用失败:', deleteError)
      ElMessage.error('删除失败，请检查网络或联系管理员')
    }
  } catch (error) {
    // 用户取消删除
    if (error !== 'cancel') {
      console.error('删除操作失败', error)
    }
  }
}

// 批量删除选中记录
async function onDeleteSelected() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  // 检查是否有非草稿状态的记录
  const nonDraftRecords = selectedRows.value.filter(row => row.states !== 0)
  if (nonDraftRecords.length > 0) {
    ElMessage.warning('只能删除草稿状态的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 获取所有选中记录的入库单编号
    const inboundListCodes = selectedRows.value.map(row => row.inboundListCode)
    
    // 逐个调用删除接口
    for (const code of inboundListCodes) {
      console.log('批量删除编号:', code)
      try {
        // 直接在URL中添加参数
        const url = `/api/PurchaseWarehousing/RemPurchaseWarehousing?inboundListCode=${encodeURIComponent(code)}`
        console.log('请求URL:', url)
        
        await http.post(url)
      } catch (err) {
        console.error(`删除编号 ${code} 失败:`, err)
      }
    }
    
    ElMessage.success('删除成功')
    getTableData() // 刷新表格
  } catch (error) {
    // 用户取消删除或接口调用失败
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

// 供应商选择相关
const supplierDialogVisible = ref(false)
const supplierSearchForm = ref({
  supplierCode: '',
  supplierName: '',
  supplierReferred: '',
  supplierRating: '',
  isLock: ''
})
const supplierTableData = ref<Supplier[]>([])
const supplierPagination = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})
const selectedSupplierId = ref('')
const selectedSupplier = ref<Supplier | null>(null)
const currentFormType = ref('') // 'add' 或 'edit'，用于标识当前操作的表单类型

// 打开供应商选择对话框
function openSupplierDialog(formType: string) {
  currentFormType.value = formType
  supplierDialogVisible.value = true
  selectedSupplierId.value = ''
  selectedSupplier.value = null
  getSupplierList()
}

// 获取供应商列表
async function getSupplierList() {
  const params = {
    pageIndex: supplierPagination.value.pageIndex,
    pageSize: supplierPagination.value.pageSize,
    supplierCode: supplierSearchForm.value.supplierCode || null,
    supplierName: supplierSearchForm.value.supplierName || null,
    supplierReferred: supplierSearchForm.value.supplierReferred || null,
    supplierRating: supplierSearchForm.value.supplierRating || null,
    isLock: supplierSearchForm.value.isLock || null
  }
  
  try {
    const response = await http.get('/api/MasterData/GetSupplierList', params)
    supplierTableData.value = response.rows || []
    supplierPagination.value.total = response.total || 0
  } catch (error) {
    console.error('获取供应商列表失败', error)
    ElMessage.error('获取供应商列表失败')
  }
}

// 搜索供应商
function searchSuppliers() {
  supplierPagination.value.pageIndex = 1
  getSupplierList()
}

// 重置供应商搜索条件
function resetSupplierSearch() {
  supplierSearchForm.value = {
    supplierCode: '',
    supplierName: '',
    supplierReferred: '',
    supplierRating: '',
    isLock: ''
  }
  supplierPagination.value.pageIndex = 1
  getSupplierList()
}

// 处理供应商分页变化
function handleSupplierPageChange(page: number) {
  supplierPagination.value.pageIndex = page
  getSupplierList()
}

// 选择供应商
function handleSupplierSelect(row: Supplier) {
  selectedSupplier.value = row
}

// 确认供应商选择
function confirmSupplierSelect() {
  if (!selectedSupplier.value) {
    ElMessage.warning('请选择一个供应商')
    return
  }
  
  // 根据当前操作的表单类型，填充对应表单的供应商信息
  if (currentFormType.value === 'add') {
    addForm.value.supplierName = selectedSupplier.value.supplierName
    addForm.value.supplierId = selectedSupplier.value.id
  } else if (currentFormType.value === 'edit') {
    editForm.value.supplierName = selectedSupplier.value.supplierName
    editForm.value.supplierId = selectedSupplier.value.id
  }
  
  supplierDialogVisible.value = false
}

// 到货通知单选择相关
const arrivalNoticeDialogVisible = ref(false)
const arrivalNoticeSearchForm = ref({
  noticeCode: '',
  noticeName: '',
  purchaseOrderCode: '',
  supplierName: '',
  deliveryDate: ''
})
const arrivalNoticeTableData = ref<ArrivalNotice[]>([])
const arrivalNoticePagination = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})
const selectedNoticeId = ref('')
const selectedNotice = ref<ArrivalNotice | null>(null)

// 打开到货通知单选择对话框
function openArrivalNoticeDialog(formType: string) {
  currentFormType.value = formType
  arrivalNoticeDialogVisible.value = true
  selectedNoticeId.value = ''
  selectedNotice.value = null
  getArrivalNoticeList()
}

// 获取到货通知单列表
async function getArrivalNoticeList() {
  const params = {
    pageIndex: arrivalNoticePagination.value.pageIndex,
    pageSize: arrivalNoticePagination.value.pageSize,
    noticeCode: arrivalNoticeSearchForm.value.noticeCode || null,
    noticeName: arrivalNoticeSearchForm.value.noticeName || null,
    purchaseOrderCode: arrivalNoticeSearchForm.value.purchaseOrderCode || null,
    supplierName: arrivalNoticeSearchForm.value.supplierName || null,
    deliveryDate: arrivalNoticeSearchForm.value.deliveryDate || null
  }
  
  try {
    const response = await http.post('/api/ArrivalNotice/GetList/GetArrivalNoticeList', params)
    arrivalNoticeTableData.value = response.rows || []
    arrivalNoticePagination.value.total = response.total || 0
  } catch (error) {
    console.error('获取到货通知单列表失败', error)
    ElMessage.error('获取到货通知单列表失败')
  }
}

// 搜索到货通知单
function searchArrivalNotices() {
  arrivalNoticePagination.value.pageIndex = 1
  getArrivalNoticeList()
}

// 重置到货通知单搜索条件
function resetArrivalNoticeSearch() {
  arrivalNoticeSearchForm.value = {
    noticeCode: '',
    noticeName: '',
    purchaseOrderCode: '',
    supplierName: '',
    deliveryDate: ''
  }
  arrivalNoticePagination.value.pageIndex = 1
  getArrivalNoticeList()
}

// 处理到货通知单分页大小变化
function handleArrivalNoticeSizeChange(val: number) {
  arrivalNoticePagination.value.pageSize = val
  getArrivalNoticeList()
}

// 处理到货通知单分页变化
function handleArrivalNoticePageChange(page: number) {
  arrivalNoticePagination.value.pageIndex = page
  getArrivalNoticeList()
}

// 处理到货通知单表格行点击
function handleNoticeRowClick(row: ArrivalNotice) {
  selectedNoticeId.value = row.id
  selectedNotice.value = row
}

// 选择到货通知单
function handleNoticeSelect(row: ArrivalNotice) {
  selectedNotice.value = row
}

// 确认到货通知单选择
function confirmArrivalNoticeSelect() {
  if (!selectedNotice.value) {
    ElMessage.warning('请选择一个到货通知单')
    return
  }
  
  // 根据当前操作的表单类型，填充对应表单的到货通知单信息
  if (currentFormType.value === 'add') {
    // 填充到货通知单编号
    addForm.value.noticeOrder = selectedNotice.value.noticeCode
    addForm.value.noticeId = selectedNotice.value.id
    // 填充到货通知单对应的采购订单编号
    addForm.value.purchaseOrderCode = selectedNotice.value.purchaseOrderCode || ''
    // 同时填充供应商信息
    addForm.value.supplierName = selectedNotice.value.supplierName
    addForm.value.supplierId = selectedNotice.value.supplierId
    // 填充到货通知单编号到informCode字段
    addForm.value.informCode = selectedNotice.value.noticeCode || ''
  } else if (currentFormType.value === 'edit') {
    // 填充到货通知单编号
    editForm.value.informCode = selectedNotice.value.noticeCode
    editForm.value.noticeId = selectedNotice.value.id
    // 填充到货通知单对应的采购订单编号
    editForm.value.purchaseOrderCode = selectedNotice.value.purchaseOrderCode || ''
    // 同时填充供应商信息
    editForm.value.supplierName = selectedNotice.value.supplierName
    editForm.value.supplierId = selectedNotice.value.supplierId
  }
  
  arrivalNoticeDialogVisible.value = false
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.page-container {
  padding-left: 32px;
  padding-right: 16px;
  padding-top: 8px;
  width: 100%;
  max-width: 100vw;
  box-sizing: border-box;
}
.filter-card {
  background: #f5f7fa;
  padding: 24px 24px 0 24px;
  border-radius: 6px;
  margin-bottom: 18px;
}
.filter-form {
  margin-bottom: 0;
}
.operation-area {
  margin: 16px 0 16px 0;
}
.table-action-btns {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
}

/* 弹窗样式 */
:deep(.custom-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.custom-dialog .el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.custom-dialog .el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.custom-dialog .el-dialog__footer) {
  padding: 10px 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-form .el-form-item {
  margin-bottom: 18px;
}

.code-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.auto-generate {
  margin-left: 10px;
  white-space: nowrap;
}

.input-with-icon {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-btn {
  margin-left: 5px;
  padding: 5px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item.is-required .el-form-item__label:before) {
  color: #f56c6c;
}

.dialog-footer {
  text-align: right;
}

/* 到货通知单选择对话框样式 */
.dialog-header {
  padding: 16px 20px;
  background-color: #409eff;
  color: white;
  font-size: 18px;
  font-weight: 600;
  border-radius: 8px 8px 0 0;
  position: relative;
}

.notice-search-area {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.notice-table-wrapper {
  margin-top: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.custom-table {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper) {
  background-color: #f5f7fa;
}

.custom-table :deep(th) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 600;
}

.notice-pagination-area {
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
}

.total-count {
  font-size: 14px;
  color: #606266;
}

/* 底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0 15px;
}

.footer-btn {
  padding: 10px 32px;
  border-radius: 4px;
  font-size: 14px;
}

.cancel-btn {
  border: 1px solid #dcdfe6;
  color: #606266;
  background: white;
}

.cancel-btn:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.save-btn {
  background: linear-gradient(135deg, #3a8ffe 0%, #3d7afd 100%);
  border: none;
}

.save-btn:hover {
  background: linear-gradient(135deg, #5da1ff 0%, #5389fc 100%);
}
</style>